import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;


public class Question5 extends Question1 {
	
	private int errorMatchOtherDigit;
	private int errorDidntMatch;
	
	public Question5(OutputGraphs graphs) {
		super(graphs);
		
	}
	public void run() throws IOException {
		noiseProb = 0.07f;
		EXAMPLES_FILE = "oneperdigit.txt";
		ExamplesInputReader reader = new ExamplesInputReader();
		ArrayList<Example> allExmples = reader.getExamples(EXAMPLES_FILE);

		checkNetworkQ5(allExmples);
		
		
		int errors = errorDidntMatch+errorMatchOtherDigit;
		System.out.println("errors :"+errors+" didnt match number "+(((errorDidntMatch)*100)/errors)+" match to another "+(((errorMatchOtherDigit)*100)/errors));
		
				
		
	}

	protected void checkNetworkQ5(ArrayList<Example> exampleSet) {
		Collection<Example> exampelsWithNoise = new LinkedList<Example>();
		//building the noise examples
		for (Example example : exampleSet) {
			for (int i = 0; i < Constants.SIZE_OF_CHANGED_EXAMPLES_Q5; i++) {
				exampelsWithNoise.add(getExampleWithChanges(example,example.digit));
				
			}
		}
		//learning set: the real examples:
		HopfieldNetwork hn = new HopfieldNetwork(exampleSet);
		int index=0;
		for (Example example : exampelsWithNoise) {

			Example returnEx=hn.reconstructExample(example);
			int ret=isExampleMatch(returnEx,exampleSet);
			if(ret==1){
				errorMatchOtherDigit++;
				//System.out.println(returnEx+" "+returnEx.digit);
			}
			if(ret==2){
				errorDidntMatch++;
				System.out.println(returnEx+" "+returnEx.digit);
			}

			index++;
		}
		
		
	}
	/**
	 * This method checks if the example fits to the example set
	 * it counts errors type 1 and errors type 2
	 * 
	 * @param returnEx
	 * @param exampleSet
	 * @return
	 */

	private int isExampleMatch(Example returnEx, ArrayList<Example> exampleSet) {
		boolean foundAnother = false;
		for (Example example : exampleSet) {
			if (example.digit==returnEx.digit)
				if (example.compareTo(returnEx)==0)
					return 0;
			if (example.compareTo(returnEx)==0)
				foundAnother =true;
			
		}
		if (foundAnother)
			return 1;
		return 2;
	}


}
